<?php

/**
 * Event form.
 *
 * @package    cpfaizenay
 * @subpackage form
 * @author     Your name here
 * @version    SVN: $Id: sfDoctrineFormTemplate.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class EventForm extends BaseEventForm
{
  public function configure() {
      $user = sfContext::getInstance()->getUser()->getGuardUser();

      $dateWidget = new sfWidgetFormI18nDate(array(
          'format' => '%day%/%month%/%year%',
        //      'month_format' => 'short_name',
          'culture' => 'fr'
      ));

    if ($this->isNew()) {
        $this->widgetSchema['updated_at'] = new sfWidgetFormInputHidden();
        $this->widgetSchema['modification_user_id'] = new sfWidgetFormInputHidden();

        $this->setDefault('creation_user_id', $user->getId());
        $this->setDefault('modification_user_id', $user->getId());

        $this->setDefault('created_at', date('d-m-Y') );
        $this->setDefault('updated_at', date('d-m-Y') );
        $this->setDefault('datetime_event', date('d-m-Y') );
    }else{
        $this->widgetSchema['updated_at'] = new sfWidgetFormJQueryDate(array(
          'culture' => 'fr',
          'date_widget' => $dateWidget,
          'image' => '/images/admin/icons/small/calendar.png',
          'config' => '{}',
        ));
        $this->getObject()->set('modification_user_id', $user->getId());
    }

    $this->widgetSchema['created_at'] = new sfWidgetFormJQueryDate(array(
      'culture' => 'fr',
      'date_widget' => $dateWidget,
      'image' => '/images/admin/icons/small/calendar.png',
      'config' => '{}',
    ));

    $this->widgetSchema['datetime_event'] = new sfWidgetFormJQueryDate(array(
      'culture' => 'fr',
      'date_widget' => $dateWidget,
      'image' => '/images/admin/icons/small/calendar.png',
      'config' => '{}',
    ));

    $this->widgetSchema['text'] = new sfWidgetFormTextareaTinyMCE(array(
          'width'  => 600,
          'height' => 350,
          'config'=> 'theme : "advanced",
                       language : "fr",
                       relative_urls : false,
                       cleanup : true,
                       plugins : "paste,table,advhr,advimage,advlink,emotions,preview,searchreplace,print,contextmenu,fullscreen,media",
                       theme_advanced_buttons1_add : "fontselect,fontsizeselect",
                       theme_advanced_buttons2_add : "media,zoom,forecolor,backcolor,separator,emotions,fullscreen",
                       theme_advanced_buttons1 : "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,formatselect,fontselect,fontsizeselect",
                       theme_advanced_buttons3 : "",
                       theme_advanced_disable : "help",
                       theme_advanced_toolbar_location : "top",
                       theme_advanced_toolbar_align : "left",
                       // theme_advanced_statusbar_location : "bottom",
                       // plugin_insertdate_dateFormat : "%d/%m/%Y",
                       // plugin_insertdate_timeFormat : "%H:%M:%S",
                       theme_advanced_resizing : true,
                       theme_advanced_resize_horizontal : false,
                       theme_advanced_resizing_use_cookie : false,
                       indentation : "10px"'
    ));

    $this->setWidget('author', new sfWidgetFormDoctrineChoice(array('model' => $this->getRelatedModelName('sfGuardUser01'), 'add_empty' => true)));
    $this->setWidget('description', new sfWidgetFormTextarea());
    $this->setWidget('copyright', new sfWidgetFormInputText());

    $this->setValidator('description', new sfValidatorString(array('required' => false)));
    $this->setValidator('author', new sfValidatorDoctrineChoice(array('model' => $this->getRelatedModelName('sfGuardUser01'), 'required' => false)));
    $this->setValidator('copyright', new sfValidatorString(array('max_length' => 100, 'required' => false)));

    $this->setDefault('author', $user->getId() );
    $this->setDefault('copyright', sfConfig::get('app_sfAssetsFile_copyright'));

    $this->setWidget('file', new sfWidgetFormInputFileEditable(array(
        'label'     => 'Image',
        'file_src'    => $this->getObject()->getAssetId() ? $this->getObject()->getSfAsset()->getUrl('small') : '',
        'edit_mode'   => !is_null($this->getObject()->getAssetId()),
        'is_image'    => !is_null($this->getObject()->getAssetId()),
        'delete_label' => 'Supprimer',
        'template'  => '<div class="file_upload">%file%<br />%input%<br />%delete% %delete_label%</div>'
    )));
    $this->validatorSchema['file_delete'] = new sfValidatorPass();

    $this->setValidator('file', new sfValidatorFile(array(
        'mime_types' => 'web_images',
        'path' => sfConfig::get('app_sfAssetsLibrary_upload_dir', 'media'),
        'required' => false
    )));

    $this->widgetSchema['asset_id'] = new sfWidgetFormInputHidden();
  }

  public function save($con = null) {
     if (null === $con){
       $con = $this->getConnection();
     }

     $folderParent = $this->createFolderParent($con);
     if($folderParent){
         $subFolder = $this->createSubFolder($folderParent, $con);
         if($subFolder){
           $this->createAsset($subFolder, $con);
         }
     }

     unset($this['file']);

     return parent::save($con);
  }

  private function createAsset($folder, $con = null) {
     $file = $this->getValue('file');

     if($this->getValue('file_delete') == true || !empty($file)){
         // destroy old asset
         if($this->getObject()->getAssetId()){
            $this->getObject()->getSfAsset()->delete($con);
         }
     }

     if(!empty($file)) {
         $asset = new sfAsset();
         $asset->setFolderId($folder['id']);
         $asset->setFilename($file->getOriginalName());
         $asset->setAuthor($this->getValue('author'));
         $asset->setCopyright($this->getValue('copyright'));
         if ($this->getValue('description') == '') {
            $asset->setDescription($file->getOriginalName());
         }

         $options = array('thumbnails' => sfConfig::get('app_sfAssetsFile_event') );

         $asset->create($file->getTempName(), true, true, $options);
         $asset->save($con);

         // Mise a jour de asset_id de News
         $this->values['asset_id'] = $asset->getId();
     }
  }

  private function createFolderParent($con = null) {
      // Création du dossier s'il n'existe pas
      $slug = 'media-evenements';
      $level = 1;
      $folder = Doctrine::getTable('sfAssetFolder')->getFolders($level, $slug)->fetchOne();

      if(!$folder){
          $folderName = 'Evénements';
          $mediaFolder = Doctrine::getTable('sfAssetFolder')->getFolders(0, 'media')->fetchOne();
          $folder = $this->createFolder($mediaFolder['id'], $folderName, $level);
      }

      return $folder;
  }

  private function createSubFolder($folderParent, $con = null){
      // Création du dossier s'il n'existe pas
      $slug = $folderParent['slug'] . '-' . date('Y') . '-' . date('m');
      $level = 2;
      $folder = Doctrine::getTable('sfAssetFolder')->getFolders($level, $slug)->fetchOne();

      if(!$folder){
          $folderName = date('Y') . '/' . date('m');
          $folder = $this->createFolder($folderParent['id'], $folderName, $level);
      }

      return $folder;
  }

  private function createFolder($id_folder, $folderName, $level = 1){

      $folder = new sfAssetFolder();
      $folder->setName($folderName);
      $folder->setLevel($level);

      $parent = sfAssetFolderTable::getInstance()->find($id_folder);
      $folder->getNode()->insertAsLastChildOf($parent);

      if($folder->create()){
        $folder->save();
      }

      return $folder;
  }
}
